<template>
  <section>
    <search-bar more-display>
      <el-row :data="condition">
        <el-col :span="8">
          <el-form-item label="货物名称" >
            <el-input   v-model="condition.name" placeholder="请输入货物品名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="货物类型"  >
            <el-select  v-model="condition.type" placeholder="请选择货物类型">
              <el-option
                v-for="item in $store.getters.GOODS_TYPE"
                :label="item.cnDictValname"
                :key="item.dictVal"
                :value="item.dictVal">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否启用" >
            <el-select  v-model="condition.status" placeholder="请选择启用状态">
              <el-option
                v-for="item in $store.getters.INDICATOR"
                :label="item.cnDictValname"
                :key="item.dictVal"
                :value="item.dictVal">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </search-bar>
    <el-col :span="24" style="margin-bottom: 10px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" @click="getTableData">刷新</el-button>
      <el-button type="danger" @click="handelBathDelete" style="width: 120px" >批量删除</el-button>
      <el-button type="primary" @click="resetCondition" style="float: right">重置</el-button>
      <el-button type="primary" @click="getTableData" style="float: right">查询</el-button>
    </el-col>
    <!--列表-->
    <el-table :data="tableData" highlight-current-row border style="width: 100%;"
              v-loading="listLoading"
              @sort-change="sortChange"
              @selection-change="selsChange" >
      <el-table-column type="selection" min-width="50" align="center">
      </el-table-column>
      <el-table-column prop="typeModel.cnDictValname" label="货物类型" width="180" align="center" >
      </el-table-column>
      <el-table-column prop="name" label="货物品名" width="400" align="center" >
      </el-table-column>
      <el-table-column prop="sorts" label="排序" width="120" align="center" >
      </el-table-column>
      <el-table-column prop="statuModel.cnDictValname" label="状态(是否启用）" width="180" align="center"  >
      </el-table-column>
      <el-table-column prop="modifyDate" label="修改日期" min-width="200" align="center" >
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="200" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="getEditBYId(scope.$index,scope.row)">编辑</el-button>
          <el-button type="primary" v-if="scope.row.status === 111002001"
                     @click="statusModify(111002002,scope.row.id,'禁用')">禁用
          </el-button>
          <el-button type="primary" v-if="scope.row.status === 111002002"
                     @click="statusModify(scope.$index,111002001,scope.row.id,'启用')">启用
          </el-button>
          <el-button type="danger" @click="handelDelete(scope.$index, scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页信息工具条-->
    <el-col :span="24" style="margin-top: 10px">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right" >
      </el-pagination>
    </el-col>
    <!--修改热门货物品名弹窗-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" size="tiny" :close-on-click-modal="false">
      <el-form :model="dialogForm" ref="dialogForm" :rules="rules" label-width="200px">
        <el-form-item label="货物类型" prop="type" >
          <el-select v-model="dialogForm.type" placeholder="请选择货物类型">
            <el-option
              v-for="item in $store.getters.GOODS_TYPE"
              :label="item.cnDictValname"
              :key="item.dictVal"
              :value="item.dictVal">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="货物品名" prop="name" >
          <el-input v-model="dialogForm.name" style="width: 200px" ></el-input>
        </el-form-item>
        <el-form-item label="货物排序" prop="sorts" >
          <el-input v-model.number="dialogForm.sorts" style="width: 200px" ></el-input>
        </el-form-item>

      </el-form><el-button @click="resetDialogForm"  style="float: right;margin-bottom: 10px">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading" style="float: right;margin-bottom: 10px;margin-right: 5px">提交</el-button>
    </el-dialog>
  </section>
</template>

<script>
import {getItemNames, saveItemName, modifyStatus, deleteItemName} from '../../api/system/ItemName';
export default {
  data () {
    return {
      token: this.$store.state.token,
      // 列表页检索条件
      condition: {
        name: '',
        type: '',
        status: ''
      },
      // 加载货物类型、状态字典
      typeDict: [],
      statusDict: [],
      // 验证规则
      rules: {
        type: [
          {required: true, type: 'number', message: '请选择货物类型'}
        ],
        name: [
          {required: true, message: '请输入热门货物品名'},
          {max: 15, message: '长度在 15字符内'}
        ],
        sorts: [
          {required: true, message: '请输入整数排序'},
          {type: 'integer', message: '请输入整数'}
        ]
      },
      // 复选框选中数据（行）
      sels: [],
      // 列表数据
      tableData: [],
      // 数据加载中提示显示控制属性
      listLoading: false,
      submitLoading: false,
      // 分页排序设置
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: null,
      sortOrder: null,
      dialogTitle: null,
      dialogForm: {
        'name': null,
        'sorts': null,
        'type': null
      },
      dialogFormVisible: false
    };
  },
  methods: {
    // 选择改变事件（包括全选/全不选、单选/单取消）传入的值为选中的复选框）
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.getTableData();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.getTableData();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.getTableData();
    },
    // 重置查询条件
    resetCondition () {
      for (let p in this.condition) {
        this.condition[p] = null;
      }
    },
    // 获取表格数据
    getTableData () {
      let str = [];
      for (let p in this.condition) {
        if (this.condition[p] !== '' && this.condition[p] !== null) {
          str.push(p + '=' + this.condition[p]);
        }
      }
      this.listLoading = true;
      getItemNames({
        token: this.token,
        page: this.currentPage,
        size: this.pageSize,
        filters: str.join(';'),
        sorts: (this.sortProp === null ? '' : (this.sortOrder === 'ascending' ? '-' : '+') + this.sortProp)
      }).then((res) => {
        if (res.data.successFlg === true) {
          this.tableData = res.data.detailModelList;
          this.currentPage = res.data.currPage;
          this.total = res.data.totalCount;
          this.pageSize = res.data.pageSize;
          this.listLoading = false;
        }
      });
    },
    // 清空弹出框表单
    resetForm () {
      // 当先点击修改，再点击新增，会出现值没有清空,修复处理
      if (this.$refs.dialogForm) {
        this.$refs.dialogForm.resetFields();
      }
      for (let p in this.dialogForm) {
        if (this.dialogForm[p] instanceof Array) {
          this.dialogForm[p] = [];
        } else {
          this.dialogForm[p] = null;
        }
      }
    },

    // 弹出新增窗体
    handleAdd () {
      this.dialogTitle = '新增';
      this.resetForm();
      this.dialogFormVisible = true;
    },

    // 弹出编辑窗体
    getEditBYId (index, row) {
      this.dialogTitle = '修改';
      this.resetForm();
      this.dialogFormVisible = true;
      this.dialogForm = Object.assign({}, row);
    },
    // 新增修改窗口取消按钮
    resetDialogForm () {
      this.dialogFormVisible = false;
    },
    // 新增修改数据提交
    handleSubmit () {
      // 表单验证
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          saveItemName(this.token, this.dialogForm).then((res) => {
            this.submitLoading = false;
            if (res.data.successFlg === true) {
              this.dialogFormVisible = false;
              this.$message.success(this.dialogTitle + '成功！');
              this.getTableData();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            console.log(error);
          });
        }
      });
    },
    // 批量删除
    handelBathDelete () {
      let id = this.sels.map(item => item.id);
      if (id.length === 0) {
        this.$message.error('请选择数据！');
        return;
      }
      this.$confirm('确认要批量删除选中商品吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        deleteItemName({
          token: this.$store.state.token,
          id: id.join(',')
        }).then((res) => {
          this.listLoading = false;
          if (res.data.successFlg === true) {
            this.$message({
              message: '恭喜删除成功！',
              type: 'success'
            });
            this.getTableData();
          } else {
            this.$message({
              message: '删除失败！',
              type: 'error'
            });
          }
        });
      });
    },
    // 单条删除
    handelDelete (index, id) {
      this.$confirm('确认删除该热门货品吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        deleteItemName({
          token: this.$store.state.token,
          id: id
        }).then((res) => {
          this.listLoading = false;
          if (res.data.successFlg === true) {
            this.$message({
              message: '恭喜删除成功！',
              type: 'success'
            });
            this.getTableData();
          } else {
            this.$message({
              message: '删除失败！',
              type: 'error'
            });
          }
        });
      }).catch(() => {
      });
    },
    // 状态变更
    statusModify (index, status, id, btnName) {
      this.$confirm('确认 ' + btnName + ' 该热门货品吗？', '提示', {
        type: 'info'
      }).then(() => {
        this.listLoading = true;
        modifyStatus(this.token, id, status).then((res) => {
          this.listLoading = false;
          if (res.data.successFlg === true) {
            this.$message({
              message: btnName + '成功！',
              type: 'success'
            });
            this.getTableData();
          } else {
            this.$message({
              message: btnName + '失败！',
              type: 'error'
            });
          }
        });
      });
    }
  },
  // 初始化数据
  mounted () {
    this.getTableData();
    this.$store.commit('initDict'); // 懒加载，用的时候可以通过$store.getters.GOODS_TYPE  获取字典数组
  }
};
</script>

<style lang="less" >

</style>
